package com.gan.ganapiclient.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.gan.ganapiclient.model.User;
import com.gan.ganapiclient.utils.SignUtil;


import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 调用第三方接口
 *
 * @author gan
 * @date 2023/5/5 11:46
 */
public class GanApiClient {

    public static final String GATEWAY_HOST = "http://localhost:8080";

    private Map<String, String> getHeader(String body) {
        Map<String, String> map = new HashMap<>();
        map.put("accessKey", "ganshao");
        map.put("body", body);
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        map.put("nonce", RandomUtil.randomNumbers(5));
        map.put("sign", SignUtil.getSign(body, secretKey));
        return map;
    }

    public GanApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    private String accessKey;

    private String secretKey;


    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get(GATEWAY_HOST + "/api/name/", paramMap);
        return result;
    }

    public String getNameByPost(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.post(GATEWAY_HOST + "/api/name/", paramMap);
        return result;
    }

    public String getUserNameByPost(User user) {
        String json = JSONUtil.toJsonStr(user);
        String result = HttpRequest.post(GATEWAY_HOST + "/api/name/user")
                .charset(StandardCharsets.UTF_8)
                .addHeaders(getHeader(json))
                .body(json)
                .execute().body();
        return result;
    }
}
